# -*- coding: utf-8 -*-
# this file function is used to read computer envirment
#
# Author：JAMO WOO
# email-jinxiangwzh#163.com
#
import logging
import os
import socket
import uuid

# 获取主机名
import requests
from PyQt5.QtCore import QStandardPaths
from bs4 import BeautifulSoup


def get_host_name():
    return socket.gethostname()


# 获取IP
def get_host_ip():
    try:
        return socket.gethostbyname(get_host_name())
    except Exception as e:
        logging.error(e)


# 获取Mac地址
def get_mac_address():
    mac = uuid.UUID(int=uuid.getnode()).hex[-12:]
    return ":".join([mac[e:e + 2] for e in range(0, 11, 2)])


def get_pc_location_en(ip_address):
    try:
        response = requests.get("https://ip.cn/index.php?ip={}".format(ip_address), timeout=10)
        soup = BeautifulSoup(response.content, 'lxml')
        a = soup.find('div', attrs={'class': 'well'})
        address = a.find_all('code')[1].text
        return address
    except Exception as e:
        logging.error(e)
        return None


def get_pc_location_zh(ip_address):
    """
    根据IP获取地理位置
    :param ip_address:
    :return:
    """
    try:
        response = requests.get("https://ip.cn/index.php?ip={}".format(ip_address), timeout=10)
        soup = BeautifulSoup(response.content, 'lxml')
        a = soup.find('div', attrs={'class': 'well'})
        b = a.find_all('p')[3].text
        address = b.replace("GeoIP: ", "")
        # 以上返回 英文或拼音的地理位置
        return address
    except Exception as e:
        logging.error(e)
        return None


def get_app_data_location():
    """
    返回用户的主目录(与QDir::homePath()相同)。在Unix系统上，这等于HOME环境变量。这个值可以是通用的，
    也可以是特定于应用程序的，但是返回的路径绝不是空的。
    Mac: "~/Library/Application Support/<APPNAME>",
         "/Library/Application Support/<APPNAME>". "<APPDIR>/../Resources"
    Windows: "C:/Users/<USER>/AppData/Roaming/<APPNAME>",
            "C:/ProgramData/<APPNAME>",
            "<APPDIR>",
            "<APPDIR>/data",
            "<APPDIR>/data/<APPNAME>"
    Linux: "~/.local/share/<APPNAME>",
           "/usr/local/share/<APPNAME>",
           "/usr/share/<APPNAME>"
    :return:
    """
    return QStandardPaths.writableLocation(QStandardPaths.AppDataLocation)


def get_cur_app_data_location(app_name="NxCom"):
    """
    获取当前软件的数据目录
    """
    home = get_app_data_location()
    app_home_path = os.path.join(home, app_name)

    if not os.path.exists(app_home_path):
        os.makedirs(app_home_path)
        logging.debug("create home directory")
    else:
        logging.debug(app_home_path + "is already exist!")

    return app_home_path


